package com.yunquan.ohana.http.observer

import com.yunquan.ohana.base.bus.RxBus
import com.yunquan.ohana.entity.EventEntity
import com.yunquan.ohana.entity.EventType
import com.yunquan.ohana.http.exception.ApiException
import com.yunquan.ohana.http.exception.ErrorType
import com.yunquan.ohana.http.exception.ExceptionEngine
import io.reactivex.rxjava3.core.Observer
import io.reactivex.rxjava3.disposables.Disposable

/**
 * $
 * @author yjp
 * @date 2020/4/1 14:49
 */
open class BaseObserver<T:Any> : Observer<T> {

    override fun onSubscribe(d: Disposable) {

    }

    override fun onNext(t: T) {
        onSuccess(t)
    }

    override fun onError(e: Throwable) {
        val ae = e as? ApiException ?: ExceptionEngine.handleException(e)
        when (ae.code) {
            ErrorType.SUCCESS -> {
                onSuccess(null)
            }
            401 -> {
                RxBus.getDefault().post(EventEntity(EventType.AUTH_FAILED, null))
            }
            else -> {
                onError(ae)
            }
        }
        onComplete()
    }

    override fun onComplete() {

    }

    open fun onError(e: ApiException){}

    open fun onSuccess(result: T?){}
}